Introduction to Machine Learning

Chapter 07: Dimensionality Reduction II — Principal Component Analysis

1. Introduction

Feature selection discards columns. Feature extraction does something more interesting: it builds a small set of new features as linear combinations of the originals, chosen so that as much of the data's variance as possible survives the reduction. Principal Component Analysis is the canonical method.

We build PCA from its mathematical foundations — the covariance matrix, eigenvalues and eigenvectors, eigendecomposition — then state the algorithm as a learning phase (fit on training data only) and an application phase. The explained variance ratio and the scree plot give us a principled way to choose how many components to keep. We finish with a full hand-computed example on the Iris dataset and a comparative case study on Adult Census Income that pits filter selection, wrapper selection and PCA against each other on the same problem.

Learning Objectives

2. Theory

2.1 Feature Extraction: Motivation of PCA

The curse of dimensionality presents several challenges:

2.2 Principal Component Analysis (PCA)

PCA is a dimensionality reduction technique that transforms data into a new coordinate system:

Applications:

2.3 Finding Direction of Maximum Variance

PCA aims to find the directions of maximum variance in high-dimensional data and projects the data onto a new subspace with equal or fewer dimensions than the original one.

Key Insight: The orthogonal axes (principal components) of the new subspace can be interpreted as the directions of maximum variance given the constraint that the new feature axes are orthogonal to each other.

Mathematical Note: If vectors \(a\) and \(b\) are orthogonal, then \(a \cdot b = 0\)

Principal component direction of maximum variance A clean infographic showing a two-dimensional elliptical dataset, its first principal component along the major axis, and the preservation of total variance under rotation. Which line points along the direction of maximum variance? Principal Component Analysis finds the axis that best follows the spread of the data. 2D dataset observations Feature 1 Feature 2 First principal component direction of maximum variance 1 Follow the long axis The widest spread is the answer. PCA rotates the coordinate system so that the new axes align with the data's natural directions. original axes PC1 rotation Key property Rotation preserves distances and total variance. TOTAL VARIANCE IS PRESERVED Σ variance of original features = Σ variance of principal components

2.4 Eigenvalues and Eigenvectors

Eigenvalues and eigenvectors are fundamental mathematical concepts used in PCA:

Let \(A\) be a square matrix. A non-zero vector \(x\) is called an eigenvector of \(A\) if and only if there exists a number (real or complex) \(\lambda\) such that: \[ A x = \lambda x \] If such a number \(\lambda\) exists, it is called an eigenvalue of \(A\). The vector \(x\) is called eigenvector associated to the eigenvalue.

Properties:

2.5 Mathematical Details: PCA Context

In PCA context, eigenvalues and eigenvectors have special properties:

2.6 PCA Algorithm: Step-by-Step Process

PCA consists of two phases: a Learning Phase and an Application Phase. The distinction matters in practice, because the parameters PCA learns — the feature means, the standard deviations and the projection matrix \(W\) — must be computed on the training set only. They are then applied unchanged to the validation and test data.

Learning Phase:

  1. Standardize the d-dimensional dataset (mean=0, variance=1 for each feature)
  2. Construct the covariance matrix
  3. Decompose the covariance matrix into its eigenvectors and eigenvalues
  4. Sort the eigenvalues by decreasing order to rank the corresponding eigenvectors

Application Phase:

  1. Select k eigenvectors, which correspond to the k largest eigenvalues, where k is the dimensionality of the new feature subspace (k ≤ d)
  2. Construct a projection matrix \(W\), from the "top" k eigenvectors
  3. Transform the d-dimensional input dataset \(X\), using the projection matrix \(W\), to obtain the new k-dimensional feature subspace

2.7 The Transformation Matrix

We construct a \(d \times k\) transformation matrix \(W\) that maps original features to reduced dimensions:

Example: 13-dimensional wine data → 3-dimensional PCA space

Key insight: W contains the selected principal components as its columns. This is the point at which the eigenvalues and eigenvectors stop being an abstract property of the covariance matrix and become a concrete dimensionality reduction step.

2.8 Key Properties of PCA

Before working through the mathematics in detail, it is worth stating the properties that make the transformed features useful:

2.9 Eigendecomposition: Decomposing a Matrix

Eigendecomposition is at the mathematical core of PCA.

The covariance matrix is a special type of square matrix: it's symmetric, meaning the matrix equals its transpose (\(A = A^T\)).

When we decompose a symmetric matrix, we get valuable properties:

Key insight: Eigenvalues and eigenvectors come in pairs: each eigenvalue has a corresponding eigenvector that shows the direction of variance.

Most important: The eigenvector with the largest eigenvalue points in the direction of maximum variance in the dataset—this becomes our first principal component.

2.10 Constructing the Covariance Matrix

The covariance matrix is a symmetric \(d \times d\) matrix where \(d\) is the number of features in the dataset. It stores pairwise covariances between all features, showing how each pair of features varies together.

Covariance between features \(x_j\) and \(x_k\): \[ \sigma_{jk} = \frac{1}{n - 1}\sum_{i = 1}^{n}(x_j^{(i)} - \mu_j)(x_k^{(i)} - \mu_k) \]

Where \(\mu_j\) and \(\mu_k\) are the sample means of features j and k respectively. Note that the sample means are zero if we standardized the dataset.

For a 3-feature dataset, the covariance matrix \(\Sigma\) looks like:

\[ \Sigma = \left[ \begin{array}{ccc} \sigma_1^2 & \sigma_{12} & \sigma_{13} \\ \sigma_{21} & \sigma_2^2 & \sigma_{23} \\ \sigma_{31} & \sigma_{32} & \sigma_3^2 \end{array} \right] \]

Important: The diagonal contains variances (\(\sigma_1^2, \sigma_2^2, \sigma_3^2\)), while off-diagonal elements are covariances (\(\sigma_{12}, \sigma_{13}, \sigma_{23}\)).

2.11 Explained Variance and Elbow Curve

Each principal component explains a portion of the total variance in the dataset. The explained variance helps determine how many principal components to keep.

Total Variance: The sum of variances of all original features equals the sum of variances of all principal components.

Explained Variance Ratio: The proportion of variance explained by each principal component.

Elbow Curve for Determining Number of Principal Components A scree plot showing explained variance ratios of 45, 30, 15, 7, and 3 percent for five principal components. The elbow occurs around the second or third component. Elbow Curve for Determining Number of Principal Components Identify the point where adding components yields diminishing returns. 1.0 0.75 0.50 0.25 0.0 1 2 3 4 5 Principal Components Explained Variance Ratio MOST INFORMATION RETAINED 45% 30% 15% 7% 3% Elbow point Curve begins to flatten Recommended range Choose 2 or 3 PCs Cumulative information 75–90% Variance by component PC1 45% PC2 30% PC3 15% PC4 7% PC5 3% The elbow balances compression with preservation of signal. s*

2.12 Explained Variance Ratio & Scree Plot

The previous section introduced explained variance informally. We now write it out in terms of the eigenvalues, which is the form used in practice to choose \(k\).

Each eigenvalue \(\lambda_j\) quantifies the variance captured by its corresponding principal component. The proportion of total variance explained by component \(j\) is:

\[ \text{EVR}_j = \frac{\lambda_j}{\sum_{i=1}^{d} \lambda_i} \]

The cumulative EVR tells us what fraction of information is retained when we keep the first \(k\) components:

\[ \text{Cumulative EVR}(k) = \sum_{j=1}^{k} \frac{\lambda_j}{\sum_{i=1}^{d} \lambda_i} \]
Scree plot for the Wine dataset Principal component variance explained for thirteen features, showing that three components retain approximately sixty-eight percent of the information. DIMENSIONALITY REDUCTION Scree plot Wine dataset · d = 13 features · variance explained by principal component Explained variance ratio Share of total information λ = 4.84 37.2% PC1 λ = 2.42 18.6% PC2 λ = 1.55 11.9% PC3 λ = 0.96 7.4% PC4 λ = 0.84 6.5% PC5 λ = 0.66 5.1% PC6 λ = 0.52 4.0% PC7 … PC8–PC13 Cumulative information Retained as components accrue PC1 37.2% PC2 Cum 55.8% PC3 Cum 67.7% The curve begins to flatten after the first three PCs. Recommended representation 3 components keep 68% of the information · approximately 10 components keep 95% s*

2.13 Hand-Calculated PCA — Iris Dataset (4 features)

Let us compute PCA on the first 8 Iris samples. Because all 4 features are measured in cm with similar ranges, we only center (we do not divide by std for pedagogical clarity).

SampleSepal LSepal WPetal LPetal W
15.13.51.40.2
24.93.01.40.2
34.73.21.30.2
44.63.11.50.2
55.03.61.40.2
65.43.91.70.4
74.63.41.40.3
85.03.41.50.2

Covariance Eigendecomposition: \(\Sigma = Q\Lambda Q^\top\), producing eigenvalues:

\[ \lambda = [4.228,\; 0.243,\; 0.078,\; 0.024] \quad\Rightarrow\quad \sum \lambda = 4.573 \]

Variance Preservation Check

📌 Standardization Rule-of-Thumb

We skipped full standardization here (cm features with similar scales). Always use full standardization when:

2.14 Case Study — Feature Engineering Showdown (Adult Census Income)

We compare four feature-engineering pipelines on the Adult Income dataset (predict income > $50K / year, ~30K rows, 14 mixed features). Evaluation metric: AUC.

Pipeline# Features UsedTraining AUCTest AUCTraining Time
Baseline (all features)140.9210.8841.0× (ref)
Filter (χ² + ANOVA)90.9100.8810.8×
Wrapper (Fwd/Bwd + KNN)70.9320.87612.4×
PCA (k = 6 components)60.9140.8881.3×
🔍 Case Study Observations (click to expand)
  • Wrapper had the highest train AUC but lowest test AUC — classic overfitting to the validation folds.
  • PCA achieved the highest test AUC using only 6 orthogonal components — decorrelation helps generalization.
  • Filter was fastest, nearly matched baseline, and is a strong first choice for quick iteration.
  • Wrapper was ~12× slower (re-trains model for every candidate feature set) — expensive at scale.

3. Interactive Examples

Example 1: PCA Visualization Example

Consider a 2D dataset with correlated features:

Principal Component Analysis Transformation A comparison of highly correlated original data and decorrelated data after PCA transformation. Principal Component Analysis Rotating correlated features into a decorrelated coordinate system Original Data Two highly correlated features x2 x1 Variance is shared across both axes PCA rotate & align After PCA Transformation Data aligned with orthogonal axes PC1 PC2 Components are statistically independent i What PCA preserves PC1 captures the direction of maximum variance; PC2 captures the remaining orthogonal variance. s*

Example 2: EVR & k-Component Selection

The Wine dataset eigenvalues (sorted) are: \([4.84,\; 2.42,\; 1.55,\; 0.96,\; 0.84,\; 0.66,\; 0.52,\; 0.35,\; 0.31,\; 0.21,\; 0.18,\; 0.15,\; 0.11]\). Click to reveal answers.

(a) What percentage of variance is explained by the first component alone?

Sum of eigenvalues = \(4.84 + 2.42 + \dots + 0.11 = 13.0\).
\(\text{EVR}_1 = \frac{4.84}{13.0} \approx 37.2\%\).

(b) What is the cumulative variance explained by the first 3 components?

\(\frac{4.84+2.42+1.55}{13.0} = \frac{8.81}{13.0} \approx 67.8\%\).

(c) A rule-of-thumb says "keep components until ≥ 95 % variance". Roughly how many components would that be for Wine?

First 9 eigenvalues sum to ≈ 12.4, giving ≈ 95.4 %. So k ≈ 9 components.

Example 3: Pipeline Winner Interpretation

Back to the Adult Census case study. Five students interpret the results. Who is correct?

StudentClaim
AliWrapper is best because its training AUC is highest (0.932).
BilalPCA is best because its test AUC is highest (0.888).
ChloeFilter is best because it's fastest.
DuaWrapper is overfitting because test AUC (0.876) < train AUC (0.932).
Bilal and Dua are both correct.
Bilal: Test-set performance on unseen data is the gold standard for generalization.
Dua: The large train–test gap for Wrapper is textbook overfitting to validation-fold feedback.
Ali is wrong (train AUC is optimistic), and Chloe confuses speed with quality.

4. Numerical Solutions

Problem 1: PCA Calculation Example

Given a dataset with the following covariance matrix:

\[ \Sigma = \begin{pmatrix} 2 & 1 \\ 1 & 2 \end{pmatrix} \]
📘 Step-by-Step Solution

Step 1: Find eigenvalues

\[ \det(\Sigma - \lambda I) = (2-\lambda)^2 - 1 = \lambda^2 - 4\lambda + 3 = 0 \] \[ \lambda = \frac{4 \pm \sqrt{16 - 12}}{2} = \frac{4 \pm 2}{2} = 3 \text{ or } 1 \]

Step 2: Find eigenvectors

For \(\lambda_1 = 3\): \[ (\Sigma - 3I)v = \begin{pmatrix} -1 & 1 \\ 1 & -1 \end{pmatrix} \begin{pmatrix} v_1 \\ v_2 \end{pmatrix} = 0 \] → \(v_1 = v_2\) → Eigenvector: \((1, 1)\) or normalized: \((\frac{1}{\sqrt{2}}, \frac{1}{\sqrt{2}})\)

For \(\lambda_2 = 1\): \[ (\Sigma - I)v = \begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix} \begin{pmatrix} v_1 \\ v_2 \end{pmatrix} = 0 \] → \(v_1 = -v_2\) → Eigenvector: \((1, -1)\) or normalized: \((\frac{1}{\sqrt{2}}, -\frac{1}{\sqrt{2}})\)

Step 3: Principal Components

PC1: \((\frac{1}{\sqrt{2}}, \frac{1}{\sqrt{2}})\) with eigenvalue 3 (explains more variance)
PC2: \((\frac{1}{\sqrt{2}}, -\frac{1}{\sqrt{2}})\) with eigenvalue 1

Problem 2: PCA Eigenvalues → Components

A 6-feature dataset produces sorted eigenvalues: \(\lambda = [3.0,\; 2.0,\; 1.0,\; 0.6,\; 0.3,\; 0.1]\).

📘 Step-by-Step Solution

Step 1: Total variance = \(\sum \lambda_i = 3.0 + 2.0 + 1.0 + 0.6 + 0.3 + 0.1 = 7.0\)

Step 2: Individual EVRs:

  • EVR₁ = 3/7 ≈ 42.9 %
  • EVR₂ = 2/7 ≈ 28.6 %   (cum ≈ 71.4 %)
  • EVR₃ = 1/7 ≈ 14.3 %   (cum ≈ 85.7 %)
  • EVR₄ = 0.6/7 ≈ 8.6 %   (cum ≈ 94.3 %)
  • EVR₅ = 0.3/7 ≈ 4.3 %   (cum ≈ 98.6 %)
  • EVR₆ = 0.1/7 ≈ 1.4 %   (cum = 100.0 %)

Step 3: How many PCs to keep for ≥ 90 % cumulative variance?

4 components give 94.3 % ≥ 90 %. So \(k = 4\).

Step 4: Compression ratio = \(\frac{k}{d} = \frac{4}{6} \approx 67\%\) of the original feature count.

5. Try It Yourself

Problem 1: PCA Eigenvalue Calculation

Given the covariance matrix:

\[ \Sigma = \begin{pmatrix} 3 & 1 \\ 1 & 3 \end{pmatrix} \]

Tasks:

  1. Find the eigenvalues
  2. Which principal component explains more variance?
  3. What proportion of total variance does each PC explain?

Solution:

  1. Eigenvalues:
    \[ \det(\Sigma - \lambda I) = (3-\lambda)^2 - 1 = \lambda^2 - 6\lambda + 8 = 0 \] \[ \lambda = \frac{6 \pm \sqrt{36 - 32}}{2} = \frac{6 \pm 2}{2} = 4 \text{ or } 2 \]
  2. Variance explanation: PC1 (λ=4) explains more variance than PC2 (λ=2)
  3. Proportions:
    • PC1: 4/(4+2) = 4/6 = 66.7%
    • PC2: 2/6 = 33.3%
Problem 2: Standardization Importance

You have a dataset with two features:

Task: What happens if you apply PCA without standardizing the data first? Which feature will dominate the first principal component?

Solution:

Problem: Without standardization, PCA will be dominated by the feature with the largest scale (Income).

Why: PCA maximizes variance. Income has much larger absolute values and thus larger variance in the original scale, even though the relative variability (coefficient of variation) might be similar.

Result: The first principal component will be heavily weighted toward Income, and Age will have minimal influence.

Solution: Always standardize features (mean=0, variance=1) before applying PCA when features have different scales.

Problem 3: Explained Variance

After applying PCA to a dataset with 10 features, you get the following eigenvalues for the principal components:

[4.5, 3.2, 1.8, 0.9, 0.6, 0.3, 0.2, 0.1, 0.05, 0.05]

Tasks:

  1. What is the total variance in the dataset?
  2. How much variance is explained by the first 3 principal components?
  3. What proportion of total variance is explained by the first 3 PCs?
  4. How many PCs would you keep to explain at least 90% of the variance?

Solution:

  1. Total variance: Sum of all eigenvalues = 4.5 + 3.2 + 1.8 + 0.9 + 0.6 + 0.3 + 0.2 + 0.1 + 0.05 + 0.05 = 11.7
  2. Variance by first 3 PCs: 4.5 + 3.2 + 1.8 = 9.5
  3. Proportion: 9.5 / 11.7 ≈ 0.812 or 81.2%
  4. PCs for 90%:
    • PC1: 4.5/11.7 ≈ 38.5%
    • PC1+PC2: (4.5+3.2)/11.7 ≈ 65.8%
    • PC1+PC2+PC3: 81.2%
    • PC1+PC2+PC3+PC4: (9.5+0.9)/11.7 ≈ 89.7%
    • PC1+PC2+PC3+PC4+PC5: (10.1+0.6)/11.7 ≈ 91.5%
    → Need 5 PCs to explain ≥90% of variance
Problem 4: EVR & k Selection

Sorted eigenvalues from a 5-feature PCA run: \([2.5,\; 1.5,\; 0.7,\; 0.2,\; 0.1]\).

  1. Compute the total variance preserved by PCA (hint: sum of eigenvalues).
  2. Compute the individual and cumulative EVR for each component.
  3. How many PCs should you keep for a ≥ 90 % cumulative-variance threshold?

Solution:

  1. Total variance = 2.5 + 1.5 + 0.7 + 0.2 + 0.1 = 5.0
  2. EVR = [50%, 30%, 14%, 4%, 2%]; cum = [50%, 80%, 94%, 98%, 100%].
  3. Keep 3 components (reaches 94% ≥ 90%).

6. Interactive Quiz

Answer all 6 questions. Click an option for instant feedback.

Your score: 0 / 6

7. Key Takeaways

8. Common Pitfalls